package com.justme.shipdfer.config;

import com.justme.shipdfer.config.properties.BeetlProperties;
import com.justme.shipdfer.enums.TemplateTypeEnum;
import org.beetl.core.GroupTemplate;
import org.beetl.core.resource.*;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
 * @author shiv
 * @create 2021/4/11 12:04 下午
 */
@Configuration
@EnableConfigurationProperties(BeetlProperties.class)
public class BeetlConfiguration {

    @Bean
    public GroupTemplate compositeResourceGroupTemplate(BeetlProperties properties) throws IOException {
        try (CompositeResourceLoader resourceLoader = new CompositeResourceLoader()) {
            // 文本资源加载器
            resourceLoader.addResourceLoader(new StartsWithMatcher(TemplateTypeEnum.TEXT.getPrefix()), new StringTemplateResourceLoader());
            // file 资源加载器
            resourceLoader.addResourceLoader(new StartsWithMatcher(TemplateTypeEnum.FILE.getPrefix()), new FileResourceLoader(properties.getFileRoot(), "utf-8"));
            // classpath 资源加载器
            resourceLoader.addResourceLoader(new StartsWithMatcher(TemplateTypeEnum.CLASSPATH.getPrefix()), new ClasspathResourceLoader("beetl"));

            // 使用默认的配置 可以修改 类路径下的 beetl.properties 文件
            org.beetl.core.Configuration cfg = org.beetl.core.Configuration.defaultConfiguration();
            return new GroupTemplate(resourceLoader, cfg);
        }
    }

}
